<template>
  <div class="custom-page out-warehouse-order-info">
    <a-form-model
      ref="modelRef"
      :model="formState"
      :rules="rules"
      :labelAlign="`left`"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 12 }"
    >
      <!-- 基本信息 -->
      <div>
        <div class="descriptions-title">基本信息</div>
        <div>
          <a-row>
            <template v-if="formState.orderType == 1">
              <a-col :span="12">
                <a-form-model-item label="客户" prop="companyTo">
                  <a-input v-model="formState.companyTo" placeholder="请输入" />
                </a-form-model-item>
              </a-col>
            </template>
            <!-- <a-col :span="12">
              <a-form-item label="有效期" name="termof">
                <a-date-picker v-model="formState.termof" placeholder="请选择" />
              </a-form-item>
            </a-col> -->
            <a-col :span="12">
              <a-form-model-item label="订单类型" prop="company">
                <a-radio-group v-model="formState.orderType" name="radioGroup" :default-value="1">
                  <a-radio :value="1"> 销售 </a-radio>
                  <a-radio :value="2"> 调拨 </a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
            <template v-if="formState.orderType == 2">
              <a-col :span="12">
                <a-form-model-item label="调拨仓库" prop="targetWarehourse">
                  <a-select
                    v-model="formState.targetWarehourse"
                    style="width: 100%"
                    placeholder="请选择"
                    :options="warehouseOptionCom"
                  ></a-select>
                </a-form-model-item>
              </a-col>
            </template>
            <a-col :span="12">
              <a-form-model-item label="来源订单号" name="orignOrderNo">
                <a-input v-model="formState.orignOrderNo" placeholder="请输入" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="外源订单号" name="sourceOrder">
                <a-input v-model="formState.sourceOrder" placeholder="请输入" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </div>
      </div>
      <!-- 规格信息 -->
      <div>
        <div>
          <div class="title-wrap">
            <div class="title descriptions-title">规格信息（{{ specsList.length }}）</div>
            <div>
              <a-button @click="addSpecs()">新增</a-button>
              <a-button style="margin-left: 15px" @click="getSpecsList()" :loading="isUpdate">刷新</a-button>
              
            </div>
          </div>
        </div>
        <div style="margin-top: 30px">
          <a-collapse v-model="activeKey">
            <a-collapse-panel v-for="(l, i) in specsList" :key="i + ''">
              <template #header>
                <a-form-model ref="formRef" :model="l" :rules="rules">
                  <div class="specs-header">
                    <div style="margin-right: 15px;">序号：{{ i + 1 }}</div>
                    <div @click.stop>
                      <a-form-model-item prop="id">
                        <a-select
                          v-model="l.id"
                          show-search
                          placeholder="规格查询"
                          option-filter-prop="children"
                          style="width: 500px"
                          :filter-option="filterOption"
                        >
                          <a-select-option
                            v-for="item in goodListComputed"
                            :key="`${item.productYlqxzcrbarmc}-${item.productSpec}`"
                            :value="`${item.productYlqxzcrbarmc}-${item.productSpec}`"
                          >
                            {{ item.productName }} - {{ item.productSpec }} - {{ item.productCpbsbmtxmc }}
                          </a-select-option>
                        </a-select>
                      </a-form-model-item>
                    </div>
                    <a-form-model-item prop="sum" style="margin-left: 30px">
                      <a-input-number
                        v-model="l.sum"
                        placeholder="请输入出库数量"
                        style="width: 200px"
                        :max="getGoodStockNum(l.id)"
                      />
                      <!-- @click.stop -->
                    </a-form-model-item>
                    <div v-if="l.id" style="margin-left: 20px">库存：{{ getGoodStockNum(l.id) }}</div>
                    <div class="right-area">
                      <a-popconfirm
                        title="是否确定删除该规格数据?"
                        ok-text="确定"
                        cancel-text="取消"
                        @confirm="delSpecs(l, i)"
                      >
                        <a-button type="link" @click.stop> 删除 </a-button>
                      </a-popconfirm>
                    </div>
                  </div>
                </a-form-model>
              </template>
              <!-- 内部数据 -->
              <div></div>
            </a-collapse-panel>
          </a-collapse>
        </div>
      </div>
      <div class="button-wrap" style="margin-top: 20px">
        <a-button type="primary" @click="submit()" :loading="loading">提交订单</a-button>
      </div>
    </a-form-model>
  </div>
</template>

<script>
const SPECS = {
  obj: {
    name: undefined,
    num: undefined,
  },
  init() {
    return JSON.parse(JSON.stringify(this.obj))
  },
}

import { queryGoodList } from '@/api/good.js'
import { outOrderAdd } from '@/api/order.js'
import { queryWarehouseList } from '@/api/warehouse.js'
import { mapState, mapGetters } from 'vuex'
export default {
  data() {
    const sumPass = (rule, value, callback) => {
      if (!value || value <= 0) {
        callback(new Error('请输入数量'))
      } else {
        callback()
      }
    }
    return {
      formState: {
        companyTo: undefined,
        orderType: 1,
        targetWarehourse: undefined,
      },
      activeKey: undefined,
      // 规格列表
      specsList: [SPECS.init()],
      goodList: [],
      isUpdate: false,
      loading: false,
      warehouseList: [],
      rules: {
        companyTo: [{ required: true, message: '请输入' }],
        targetWarehourse: [{ required: true, message: '请选择' }],
        id: [{ required: true, message: '请选择' }],
        sum: [{ validator: sumPass }],
      },
      
    }
  },
  watch: {
    'formState.orderType': {
      handler: function (n, o) {
        this.$refs.modelRef && this.$refs.modelRef.clearValidate()
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    ...mapGetters(['userInfo']),
    ...mapState({ showWarehouseSize: (s) => s.business.showWarehouseSize }),
    goodListComputed() {
      const chooseArr = this.specsList.map((e) => e.id).filter((f) => f) || []
      return this.goodList.filter((e) => chooseArr.indexOf(`${e.productYlqxzcrbarmc}-${e.productSpec}`) == -1) || []
    },
    warehouseOptionCom() {
      const { userInfo } = this
      return this.warehouseList.filter((f) => f.id != userInfo.currWarehouse) || []
    },
    tokenHeader() {
      let head = { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) }
      let tenantid = Vue.ls.get(TENANT_ID)
      if (tenantid) {
        head['tenant-id'] = tenantid
      }
      return head
    },
    
  },
  mounted() {
    this.getSpecsList()
    this.getWarehouseList()
  },
  methods: {
    // 计算库存
    getGoodStockNum(key) {
      let num = 0
      const row = this.goodList.filter((f) => `${f.productYlqxzcrbarmc}-${f.productSpec}` == key)
      if (row && row.length > 0) {
        num = row[0].amount
      }
      return num
    },
    async getWarehouseList() {
      try {
        const { showWarehouseSize } = this
        const r = await queryWarehouseList({ pageNo: 1, pageSize: showWarehouseSize })
        this.warehouseList = r.result.records.map((e) => {
          return { ...e, label: e.name, value: e.name }
        })
      } catch (_) {}
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    addSpecs() {
      this.specsList.push(SPECS.init())
    },
    delSpecs(e, i) {
      this.specsList.splice(i, 1)
    },
    async getSpecsList() {
      try {
        const params = { pageNo: 1, pageSize: 100 }
        this.isUpdate = true
        const r = await queryGoodList(params)
        this.goodList = r.result
      } catch (_) {}
      this.isUpdate = false
    },
    async submit() {
      const self = this
      try {
        await self.$refs.modelRef.validate()
        const formRefs = self.$refs.formRef
        if (formRefs && formRefs.length > 0) {
          for (let i = 0; i < formRefs.length; i++) {
            await formRefs[i].validate()
          }
        }
        const { formState } = self
        const arr = self.specsList.map((e) => {
          const r = self.goodList.filter((f) => `${f.productYlqxzcrbarmc}-${f.productSpec}` == e.id)
          if (r && r.length > 0) {
            e.productCpbsbmtxmc = r[0].productCpbsbmtxmc
            e.productName = r[0].productName
            e.productType = r[0].productType
            e.productYlqxzcrbarmc = r[0].productYlqxzcrbarmc
            e.productZxxsdycpbs = r[0].productZxxsdycpbs
            e.productZxxsydydsl = r[0].productZxxsydydsl
            e.specName = r[0].productSpec
            delete e.id
          }
          return { ...e }
        })
        const params = {
          ...formState,
          outOrderVtoSpecLists: arr,
        }
        self.loading = true
        await outOrderAdd(params)
        self.$message.success('操作成功!')
        self.$router.go(-1)
      } catch (_) {}
      self.loading = false
    },
   
  },
}
</script>

<style lang="scss" scoped>
.title-wrap {
  display: flex;
  .title {
    margin-right: 30px;
  }
}
.descriptions-title {
  font-size: 20px;
  font-weight: 650;
}
.specs-header {
  display: flex;
  align-items: center;
}
.specs-header {
  .ant-form-item {
    margin-bottom: 0;
  }
  .right-area {
    flex: 1;
    display: flex;
    justify-content: flex-end;
  }
}
.out-warehouse-order-info {
  :deep(.ant-collapse-content-box) {
    padding: 0;
  }
}
.button-wrap {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
